package com.hz.house.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hz.house.bean.vo.WxMiniCheck;
import com.hz.house.common.ResultUtil;
import com.hz.house.config.WxConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class CommonService {

	@Resource
	private RestTemplate restTemplate;
	   
	@Autowired
	private RedisTemplate<String,Object> redis;
	
	@Autowired
	private WxConfig wxConfig;
	
	private ExecutorService es = Executors.newFixedThreadPool(10);
	
	
	/**检查内容是否敏感的接口*/
	private static final String CHECK_CONTENT_HOST= "https://api.weixin.qq.com/wxa/msg_sec_check";

	/**检查内容是否敏感的接口*/
	private static final String CHECK_MEDIA_HOST= "https://api.weixin.qq.com/wxa/media_check_async";
	
	/**小程序的token获取url*/
	private static final String XIAOCHENGXU_ACCTK_HOST = "https://api.weixin.qq.com/cgi-bin/token";
	
	/**小程序的微信服务apitokenkey*/
	public static String EVALUATE_WX_ACCTC_REDIS_KEY = "evaluate_wxacctk";

	/**买房好帮手微信公众号token*/
	public static String EVALUATE_WX_MFHBSGZH_REDIS_KEY = "evaluate_wxgzhacctk";

	/**买房好帮手微信公众号appId*/
	private static String GZH_APP_ID = "wx91494395b916ce00";

	/**买房好帮手微信公众号secret*/
	private static String GZH_SECRET = "db81d86a4c778c570b3a7a06ba04f9e0";

	/**百度的apikey**/
	private static String BAIDU_API_KEY = "48KGwI7a8NmmVT9TsXyxH3WC";

	/**百度api密钥**/
	private static String BAIDU_API_SECRET = "5RESUu9p62Z4gUmekEhsYGou8mFxRmGk";

	/**百度token缓存redis的key**/
	private static String BAIDU_ACCTK_KEY = "baidu_acctk";

	/**微信验证铭感内容**/
	public Boolean wxMiniCheck(WxMiniCheck wxMiniCheck){
		String content = wxMiniCheck.getContent();
		boolean isWrong = true;
		if (!StringUtils.isEmpty(content)){
			isWrong = checkContent(content);
		}
		if (isWrong){
			String mediaUrl = wxMiniCheck.getMediaUrl();
			Integer mediaType = wxMiniCheck.getMediaType();
			if (!ObjectUtils.isEmpty(mediaUrl) && !ObjectUtils.isEmpty(mediaType)){
				isWrong = checkMedia(mediaUrl, mediaType);
			}
		}
		return isWrong;
	}

	
	/**检查文字内容是否有敏感内容:使用腾讯和百度双重校验*/
	public Boolean checkContent(String content) {
        String url = CHECK_CONTENT_HOST + "?access_token=" +getWxMiniProgramAcctk();
        Map<String, Object> map = new HashMap<>();
        map.put("content", content);
        JSONObject json = new JSONObject(map);
        String res = doPostSendMsg(json.toJSONString(), url);
        log.info("腾讯云校验结果:"+res);
        JSONObject result = JSON.parseObject(res);
        boolean x = result.getIntValue("errcode") == 0;
        return x;
        //如果腾讯校验通过了，那么则还要使用百度校验一遍.2019-12-23 取消百度校验。
        //return this.checkContentByBaidu(content);
    }

	/**检查文字内容是否有敏感内容:使用腾讯和百度双重校验*/
	public Boolean checkMedia(String mediaUrl, Integer mediaType) {
		String url = CHECK_MEDIA_HOST + "?access_token=" +getWxMiniProgramAcctk();
		Map<String, Object> map = new HashMap<>(2);
		map.put("media_url", mediaUrl);
		map.put("media_type", mediaType);
		JSONObject json = new JSONObject(map);
		String res = doPostSendMsg(json.toJSONString(), url);
		log.info("腾讯云校验结果:"+res);
		JSONObject result = JSON.parseObject(res);
		return result.getIntValue("errcode") == 0;
	}
	
	/**封装http请求发送post,返回接口的结果 */
	private String doPostSendMsg(String jsonData,String url) {
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_JSON);
		HttpEntity<String> entity = new HttpEntity<String>(jsonData, headers);
		String json = restTemplate.postForObject(url, entity, String.class);
		return json;
	}
	
	public String getWxMiniProgramAcctk() {
		String tk = (String) this.redis.opsForValue().get(EVALUATE_WX_ACCTC_REDIS_KEY);
		if(tk==null) {
			tk = this.accessTokenAPI();
			this.redis.opsForValue().set(EVALUATE_WX_ACCTC_REDIS_KEY,tk,2, TimeUnit.HOURS);
		}
		return tk;
	}

	public String getMaiFGzhAcctk(){
		String tk = (String) this.redis.opsForValue().get(EVALUATE_WX_MFHBSGZH_REDIS_KEY);
		if(tk==null) {
			tk = this.accessGzhTokenAPI();
			this.redis.opsForValue().set(EVALUATE_WX_MFHBSGZH_REDIS_KEY,tk,2, TimeUnit.HOURS);
		}
		return tk;
	}

	public void homePageCacheService() {
		String tk = this.accessTokenAPI();
		this.redis.opsForValue().set(EVALUATE_WX_ACCTC_REDIS_KEY,tk,2, TimeUnit.HOURS);
	}
	
	 private String accessTokenAPI() {
	        String url = XIAOCHENGXU_ACCTK_HOST + "?grant_type=client_credential&appid={appid}&secret={secret}";
	        // 向微信接口发起请求
	        Map<String, String> params = new HashMap<>(4);
	        params.put("secret", wxConfig.getSecret());
	        params.put("appid", wxConfig.getAppid());
	        String result = restTemplate.getForObject(url, String.class, params);
	        JSONObject json = JSON.parseObject(result);
	        return json.getString("access_token");
	}

	private String accessGzhTokenAPI() {
		String url = XIAOCHENGXU_ACCTK_HOST + "?grant_type=client_credential&appid={appid}&secret={secret}";
		// 向微信接口发起请求
		Map<String, String> params = new HashMap<>(4);
		params.put("secret", GZH_SECRET);
		params.put("appid", GZH_APP_ID);
		String result = restTemplate.getForObject(url, String.class, params);
		JSONObject json = JSON.parseObject(result);
		return json.getString("access_token");
	}
	
	 /**在公共的线程池执行 */
	 public void runInThreadPool(Runnable worker) {
		 this.es.execute(worker);
	 }
	 
	 /**获取百度的apitoken**/
	 private static String baiduTokenApi = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials"
	 		+ "&client_id="+BAIDU_API_KEY+"&client_secret="+BAIDU_API_SECRET+"";
	 public String getBaiDuApiAcctk() {
		 
		 String bdk = (String) this.redis.opsForValue().get(BAIDU_ACCTK_KEY);
		 if(StringUtils.isEmpty(bdk)) {
			 //初始化
			String res =  this.doPostSendMsg("", baiduTokenApi);
			System.out.println(res);
			JSONObject jo = JSON.parseObject(res);
			bdk = jo.getString("access_token");
			this.redis.opsForValue().set(BAIDU_ACCTK_KEY, bdk, 3, TimeUnit.DAYS);
		 }
		 return bdk;
	 }
	 
	 public boolean checkContentByBaidu(String content) {
		 String url = "https://aip.baidubce.com/rest/2.0/antispam/v2/spam?access_token="+getBaiDuApiAcctk();
		 MultiValueMap<String, Object> postParameters = new LinkedMultiValueMap<>();
		 postParameters.add("content", content);
		 HttpHeaders headers = new HttpHeaders();
		 headers.add("Content-Type", "application/x-www-form-urlencoded");
		 HttpEntity<MultiValueMap<String, Object>> r = new HttpEntity<>(postParameters, headers);
		 String res = restTemplate.postForObject(url, r, String.class);
		 System.out.println(res);
		 JSONObject jo = JSON.parseObject(res);
		 JSONObject result = jo.getJSONObject("result");
		 int x = result.getInteger("spam");
		 log.info("内容："+content+",百度校验结果："+x);
		return x==0; 
	 }
	 
	 
	 public Object getXiaoChengToken() {
			return ResultUtil.ok(null,this.getWxMiniProgramAcctk());
	}

	public Object getMaiFGzhTk(){
	 	return ResultUtil.ok(null,this.getMaiFGzhAcctk());
	}
}
